﻿using System;
using System.Linq;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel.DataAnnotations;
using APH.Parl2.Client.Parl2.DynamicData.DataAnnotations;

namespace APH.Parl2.Client.Parl2.DynamicData
{
    public partial class ValuesList_EditField : System.Web.DynamicData.FieldTemplateUserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SetUpValidator(RequiredFieldValidator1);

            if (DropDownList1.Items.Count == 0)
            {
                // add [Not Set] in insert mode as the field would
                // otherwise just take on the first value in the list
                // if the user clicks save without changing it.
                if (!Column.IsRequired || Mode == DataBoundControlMode.Insert)
                {
                    DropDownList1.Items.Add(new ListItem("[Not Set]", ""));
                }

                // fill the dropdown list with the 
                // values in the ValuesList attribute
                PopulateListControl(DropDownList1);
            }
        }

        /// <summary>
        /// Populates a list control with all the values from a parent table.
        /// </summary>
        /// <param name="listControl">The list control to populate.</param>
        protected new void PopulateListControl(ListControl listControl)
        {
            var uiHint = Column.GetAttribute<UIHintAttribute>();
            if (uiHint == null || uiHint.ControlParameters.Count == 0 || !uiHint.ControlParameters.Keys.Contains("ValueList"))
                throw new InvalidOperationException(String.Format(
                    "ValuesList for FieldTemplate {0} field is missing from UIHint",
                    Column.Name));

            var valuesList = ValuesListAttribute(uiHint.ControlParameters["ValueList"].ToString());
            if (valuesList.Count() == 0)
                throw new InvalidOperationException(String.Format(
                    "ValuesList for FieldTemplate {0} field, is empty",
                    Column.Name));

            listControl.Items.AddRange(valuesList);
        }

        public ListItem[] ValuesListAttribute(String values)
        {
            var items = values.Split(new char[] { ',', ';' });
            var listItems = (from item in items
                             select new ListItem()
                             {
                                 Text = item,
                                 Value = item
                             }).ToArray();
            return listItems;
        }

        // added page init to hookup the event handler
        protected override void OnDataBinding(EventArgs e)
        {
            if (Mode == DataBoundControlMode.Edit)
            {
                ListItem item = DropDownList1.Items.FindByValue(FieldValueString);
                if (item != null)
                    DropDownList1.SelectedValue = FieldValueString;
            }

            if (Mode == DataBoundControlMode.Insert)
                DropDownList1.SelectedIndex = 0;

            base.OnDataBinding(e);
        }

        /// <summary>
        /// Provides dictionary access to all data in the current row.
        /// </summary>
        /// <param name="dictionary">The dictionary that contains all the new values.</param>
        protected override void ExtractValues(IOrderedDictionary dictionary)
        {
            // If it's an empty string, change it to null
            string val = DropDownList1.SelectedValue;
            if (val == String.Empty)
                val = null;

            dictionary[Column.Name] = ConvertEditedValue(val);
        }

        /// <summary>
        /// Gets the data control that handles the data field in a field template.
        /// </summary>
        /// <value></value>
        /// <returns>
        /// A data control that handles the data field in a field template.
        /// </returns>
        public override Control DataControl
        {
            get
            {
                return DropDownList1;
            }
        }
    }
}
